import {
  EllipsisOutlined,
  UserOutlined,
  CameraOutlined,
  FileOutlined,
  InfoCircleOutlined,
  LinkOutlined,
} from '@ant-design/icons-vue';
import { AppComponentBase } from '/@/shared/component-base';
import { defineComponent } from 'vue';
import {
  abpService,
  abpSignalrService,
  appSessionService,
  BlockUserInput,
  ChatServiceProxy,
  FriendDto,
  FriendshipServiceProxy,
  FriendshipState,
  ProfileServiceProxy,
  UnblockUserInput,
} from '/@/shared';
import { ChatFriendDto } from '/@/shared/components/quick-chat/interfaces';
import AddFriendComponent from './add-friend.vue';
import { AppConsts } from '/@/abpPro/AppConsts';
import GChatMessage from './chat-message.vue';
import _ from 'lodash';

export default defineComponent({
  name: 'chat',
  components: {
    UserOutlined,
    CameraOutlined,
    FileOutlined,
    EllipsisOutlined,
    InfoCircleOutlined,
    LinkOutlined,
    GChatMessage,
  },
  mixins: [AppComponentBase],
  props: {
    isShow: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 是否开启了多租户
      isMultiTenancyEnabled: false,
      // 发送消息的内容
      chatMessage: '',
      // 过滤/搜索用户的查询条件
      filterText: '',
      // 聊天的抽屉
      chatDrawer: false,
      // 好友列表
      friendList: [] as ChatFriendDto[],
      // 过滤后的好友列表
      filterFriendList: [] as ChatFriendDto[],
      // 用于触发update钩子的
      updateTag: '',
      // 当前用户的头像
      currentProfilePicture: '/assets/images/user.png',
      // 当前用户的信息
      currentUserInfo: abpService.loginInfo.user,
      // 文件上传的地址
      uploadFileUrl: '',
      // 文件列表
      uploadfileList: [] as any[],
      // 文件上传的请求头
      uploadHeaders: {},
      // 是否锁定
      isBlock: false,
      // 被锁定的好友
      blockFriendList: [] as ChatFriendDto[],
      profileServiceProxy: new ProfileServiceProxy(),
      chatService: new ChatServiceProxy(),
      friendshipService: new FriendshipServiceProxy(),
      signalrService: abpSignalrService,
    };
  },
  watch: {
    chatDrawer(newVal) {
      if (!newVal) {
        this.filterFriends();
      }
    },
  },
  created() {
    this.isMultiTenancyEnabled = this.multiTenancy.isEnabled;
    this.filterFriends();
    this.getCurrentProfilePicture();
    this.registerEvents();
    this.getFileUploadUrl();
    Object.assign(this.uploadHeaders, {
      Authorization: 'Bearer ' + abp.auth.getToken(),
    });
  },
  updated() {
    this.updateScrollPoint();
  },
  methods: {
    /**
     * 获取上传文件地址
     */
    getFileUploadUrl() {
      this.uploadFileUrl =
        AppConsts.remoteServiceBaseUrl + '/api/services/app/SysFile/CreateReturnSysFile';
    },
    /**
     * 获取当前用户的头像
     */
    getCurrentProfilePicture() {
      this.loading = true;
      const pid = abpService.loginInfo.user.profilePictureId;
      if (!pid) {
        this.currentProfilePicture = '/assets/images/user.png';
      } else {
        this.profileServiceProxy
          .getProfilePictureById(pid)
          .finally(() => (this.loading = false))
          .then(async (result) => {
            if (result && result.profilePicture) {
              const profilePreviewImage = 'data:image/jpeg;base64,' + result.profilePicture;
              this.currentProfilePicture = profilePreviewImage;
            }
          });
      }
    } /* 关闭抽屉 */,
    onClose() {
      this.$emit('closeChat');
    },
    /* 弹出聊天内容抽屉 */
    toMessageDetail(user: ChatFriendDto): void {
      abpSignalrService.choUser(user, () => {
        this.filterFriends();
        this.chatDrawer = true;
      });
    },
    // 过滤好友列表
    filterFriends(state?: FriendshipState): void {
      this.friendList = abpSignalrService.friends;
      this.filterFriendList = this.friendList.filter(
        (x) =>
          (x.state == FriendshipState.Accepted || x.state == 1) &&
          this.getShownUserName(x.friendTenancyName, x.friendUserName)
            .toLocaleLowerCase()
            .includes(this.filterText.toLocaleLowerCase()),
      );
      this.blockFriendList = this.friendList.filter(
        (x) =>
          x.state == FriendshipState.Blocked &&
          this.getShownUserName(x.friendTenancyName, x.friendUserName)
            .toLocaleLowerCase()
            .includes(this.filterText.toLocaleLowerCase()),
      );
      this.updateTag = new Date() + '1';
    },
    // 对用户显示的名字做处理
    getShownUserName(tenanycName: string | undefined, userName: string | undefined): string {
      if (!this.isMultiTenancyEnabled) {
        return userName as string;
      }
      return (tenanycName ? tenanycName : '.') + '\\' + userName;
    },
    // 发送消息
    sendMessage(event?: any): void {
      if (event) {
        event.preventDefault();
        event.stopPropagation();
      }

      if (!this.chatMessage) {
        return;
      }

      const tenancyName = appSessionService.tenant ? appSessionService.tenant.tenancyName : null;
      abpSignalrService.sendMessage(
        {
          tenantId: abpSignalrService.selectedUser.friendTenantId,
          userId: abpSignalrService.selectedUser.friendUserId,
          message: this.chatMessage,
          tenancyName: tenancyName,
          userName: this.currentUserInfo.userName,
          profilePictureId: this.currentUserInfo.profilePictureId,
        },
        () => {
          this.chatMessage = '';
          this.updateScrollPoint();
        },
      );
    },
    // 更新滚动条的位置到最底端
    updateScrollPoint() {
      if (this.chatDrawer) {
        this.$nextTick(() => {
          const div = document.getElementById('chat-message-content') || ({} as any);
          div.scrollTop = div.scrollHeight;
        });
      }
    },
    // 注册需要监听的事件
    registerEvents() {
      abp.event.on('app.chat.messageReceived', (message) => {
        if (message.targetUserId == abpSignalrService.selectedUser.friendUserId) {
          this.updateScrollPoint();
        }
        this.filterFriends();
      });
      abp.event.on('app.chat.userConnectionStateChanged', (data) => {
        abpSignalrService.onUserConnectionStateChanged(data);
        this.filterFriends();
      });
      abp.event.on('app.chat.userStateChanged', (data) => {
        abpSignalrService.onUserStateChanged(data.friend, data.state);
      });
      abp.event.on('app.chat.friendshipRequestReceived', (data, isOwnRequest) => {
        this.onFriendshipRequestReceived(data, isOwnRequest);
      });
    },
    // 添加朋友
    addFriend() {
      this.modalHelper
        .create(AddFriendComponent, { searchText: this.filterText })
        .subscribe((res) => {
          this.filterText = '';
          //   const friend = res as ChatFriendDto;
          //   abpSignalrService.getUserProfile(friend.friendUserId).then((res) => {
          //     friend.friendProfilePicture = res;
          //     this.friendList.push(friend);
          //     this.filterFriends();
          //   });
        });
    },
    // 上传图片
    uploadImage(info: { file: any; fileList: any }) {
      if (info.file.status === 'error') {
        this.notify.error(this.l('FileSavedFailed'));
        return;
      }
      if (info.file.status === 'done') {
        this.notify.success(this.l('SavedSuccessfully'));
        let fileList = [...info?.fileList];
        fileList = fileList.slice(-2);
        fileList.map((file) => {
          if (file.response) {
            file.url = file.response.result.path;
            this.uploadfileList = [];
            this.chatMessage = '[image]fileUrl=' + file.url;
            this.sendMessage();
            return;
          }
        });
      }
    },
    // 上传文件
    uploadFile(info: { file: any; fileList: any }) {
      if (info.file.status === 'error') {
        this.notify.error(this.l('FileSavedFailed'));
        return;
      }
      if (info.file.status === 'done') {
        console.log(info);
        this.notify.success(this.l('SavedSuccessfully'));
        let fileList = [...info?.fileList];
        fileList = fileList.slice(-2);
        fileList.map((file) => {
          if (file.response) {
            file.url = file.response.result.path;
            this.uploadfileList = [];
            this.chatMessage =
              '[file]fileUrl=' + file.url + 'fileName=' + file.response.result.fileName;
            this.sendMessage();
            return;
          }
        });
      }
    },
    // 分享当前网页链接
    shareCurrentLink() {
      this.chatMessage = '[link]{"message":"' + window.location.href + '"}';
      this.sendMessage();
    },
    // 锁定用户
    block(): void {
      this.chatMessage = '';
      const user = abpSignalrService.selectedUser;
      const blockUserInput = new BlockUserInput();
      blockUserInput.tenantId = user.friendTenantId;
      blockUserInput.userId = user.friendUserId;

      this.friendshipService.blockUser(blockUserInput).then(() => {
        this.notify.info(this.l('UserBlocked'));
        this.filterFriends();
      });
    },
    // 取消锁定用户
    unblock(): void {
      const user = abpSignalrService.selectedUser;
      const unblockUserInput = new UnblockUserInput();
      unblockUserInput.tenantId = user.friendTenantId;
      unblockUserInput.userId = user.friendUserId;

      this.friendshipService.unblockUser(unblockUserInput).then(() => {
        this.notify.info(this.l('UserUnblocked'));
        this.filterFriends();
      });
    },
    // 监听添加好友事件
    onFriendshipRequestReceived(data, isOwnRequest) {
      if (!isOwnRequest) {
        abp.notify.info(this.l('UserSendYouAFriendshipRequest', data.friendUserName));
      }

      if (
        !_.filter(
          abpSignalrService.friends,
          (f) => f.friendUserId === data.friendUserId && f.friendTenantId === data.friendTenantId,
        ).length
      ) {
        const friend = data as ChatFriendDto;
        abpSignalrService.getUserProfile(friend.friendUserId).then((res) => {
          friend.friendProfilePicture = res;
          this.friendList.push(friend);
          this.filterFriends();
        });
      }
    },
  },
});
